package com.sixkey.aspect;

/**
 * ClassName: OperationLogAspect
 * Package: com.sixkey.aspect
 * Description:
 *
 * @Author: @weixueshi
 * @Create: 2023/9/10 - 0:15
 * @Version: v1.0
 */

import com.sixkey.annotation.OperationLog;
import com.sixkey.entity.Log;
import com.sixkey.utils.IpUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.time.LocalDateTime;

/**
 * 操作日志记录切面
 */

@Slf4j
@Aspect
@Component
public class OperationLogAspect {
    @Pointcut("@annotation(com.sixkey.annotation.OperationLog)")
    public void pointcut(){}

    @Autowired
    private EventPublistener eventPublistener;


    /**
     * 在切点之后切入
     */
    @After("pointcut()")
    public void deAfter(JoinPoint joinPoint){
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        Method method = methodSignature.getMethod();
        //获取方法上的注解
        OperationLog logAnnotation = method.getAnnotation(OperationLog.class);
        //获取系统基本信息

        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String requestMethod = request.getMethod();
        String ip = IpUtils.getIpAddr(request);
        Log operLog = new Log();
        operLog.setMethod(requestMethod);
        operLog.setIp(ip);
        operLog.setOperation(logAnnotation.value());
        //TODO:需要设置登录用户的名称
        operLog.setName("swx");
        operLog.setCreateTime(LocalDateTime.now());
        //发布消息
        eventPublistener.publishEvent(operLog);
        log.info("========用户操作日志记录发送成功，内容为：{}==========",operLog);
    }
}
